package org.xwalk.core.internal;

import java.io.BufferedWriter;
import java.io.File;
import java.util.Map;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class XWalkHitTestResultBridge extends XWalkHitTestResultInternal {
    private XWalkCoreBridge coreBridge;
    private Object wrapper;

    public Object getWrapper() {
        return wrapper;
    }

    private ReflectMethod enumtypeClassValueOfMethod = new ReflectMethod();

    private Object Converttype(type type) {
        return enumtypeClassValueOfMethod.invoke(type.toString());
    }


    private XWalkHitTestResultInternal internal;

    XWalkHitTestResultBridge(XWalkHitTestResultInternal internal) {
        this.internal = internal;
        reflectionInit();
    }

    @Override
    public type getType() {
        if (getTypeMethod == null || getTypeMethod.isNull()) {
            return getTypeSuper();
        } else {
            return (type)getTypeMethod.invoke();
        }
    }

    public type getTypeSuper() {
        type ret;
        if (internal == null) {
            ret = super.getType();
        } else {
            ret = internal.getType();
        }
        if (ret == null) return null;
        return ret;
    }

    private ReflectMethod getTypeMethod = new ReflectMethod(null, "getType");

    @Override
    public String getExtra() {
        if (getExtraMethod == null || getExtraMethod.isNull()) {
            return getExtraSuper();
        } else {
            return (String)getExtraMethod.invoke();
        }
    }

    public String getExtraSuper() {
        String ret;
        if (internal == null) {
            ret = super.getExtra();
        } else {
            ret = internal.getExtra();
        }
        if (ret == null) return null;
        return ret;
    }

    private ReflectMethod getExtraMethod = new ReflectMethod(null, "getExtra");


    void reflectionInit() {
        coreBridge = XWalkCoreBridge.getInstance();
        if (coreBridge == null) return;

        ReflectConstructor constructor = new ReflectConstructor(
                coreBridge.getWrapperClass("XWalkHitTestResult"), Object.class);
        try {
            wrapper = constructor.newInstance(this);
        } catch (UnsupportedOperationException e) {
            return;
        }

        enumtypeClassValueOfMethod.init(null,
                coreBridge.getWrapperClass("XWalkHitTestResult$type"), "valueOf", String.class);

        getTypeMethod.init(wrapper, null,
                "getType");
        getExtraMethod.init(wrapper, null,
                "getExtra");
    }
}
